package com.zmzncs.lmtc.module.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.common.pojo.Rest;
import com.zmzncs.lmtc.common.util.RestUtil;
import com.zmzncs.lmtc.module.system.dao.RolePermissionMapper;
import com.zmzncs.lmtc.module.system.pojo.role_permission.RolePermission;
import com.zmzncs.lmtc.module.system.pojo.role_permission.RolePermissionDTO;
import com.zmzncs.lmtc.module.system.service.RolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2020-03-06
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    /**
     *  分配权限
     */
	@Override
	@Transactional
	public Rest assignsPermission(Long roleId, Long[] permissionIds) {
		//先删除角色权限关联表
		rolePermissionMapper.deleteRolePermission(roleId);

		//添加角色权限关联表
		if(permissionIds != null && permissionIds.length != 0) {
			for(Long permissionId: permissionIds) {
				RolePermission rolePermission = new RolePermission();
				rolePermission.setRoleId(roleId);
				rolePermission.setPermissionId(permissionId);
				rolePermissionMapper.insert(rolePermission);
			}
			return RestUtil.success();
		}
		return RestUtil.warning("没有权限");
	}



	/**
	 * 根据角色id查询角色权限id数组
	 */
	@Override
	public Long[] getPermissionIdsByRoleId(Long roleId) {
		List<RolePermissionDTO> rolePermissionDTOList = rolePermissionMapper.getRolePermissionByRoleId(roleId);

		Long[] permissionIds = new Long[rolePermissionDTOList.size()];
		for(int i=0; i< rolePermissionDTOList.size(); i++){
			permissionIds[i] = rolePermissionDTOList.get(i).getPermissionId();
		}
		return permissionIds;
	}

	/**
	 * 根据角色id查询角色权限数组
	 */
	@Override
	public List<RolePermissionDTO> getRolePermissionListByRoleId(Long roleId) {
		List<RolePermissionDTO> rolePermissionDTOList = rolePermissionMapper.getRolePermissionByRoleId(roleId);
		return rolePermissionDTOList;
	}

}
